<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>html5 拖拽</title>
  <style>
    #draggable {
      width: 200px;
      height: 20px;
      text-align: center;
      background: white;
    }

    .dropzone {
      width: 200px;
      height: 20px;
      background: blueviolet;
      margin-bottom: 10px;
      padding: 10px;
    }
  </style>
</head>

<body>
  <!-- html5 拖拽 -->
  <div class="dropzone">
    <div id="draggable" draggable="true" ondragstart="event.dataTransfer.setData('text/plain',null)">
      This div is draggable
    </div>
  </div>
  <div class="dropzone"></div>
  <div class="dropzone"></div>
  <div class="dropzone"></div>

  <script>
    var dragged;

    /* 可拖动的目标元素会触发事件 */
    document.addEventListener("drag", function (event) {

    }, false);

    document.addEventListener("dragstart", function (event) {
      console.log("dragstart",event.target)
      // 保存拖动元素的引用(ref.)
      dragged = event.target;
      // 使其半透明
      event.target.style.opacity = .5;
    }, false);

    document.addEventListener("dragend", function (event) {
      console.log("dragend",event.target)
      // 重置透明度
      event.target.style.opacity = "";
    }, false);

    /* 放下目标节点时触发事件 */
    document.addEventListener("dragover", function (event) {
      console.log("dragover",event.target)
      // 阻止默认动作
      event.preventDefault();
    }, false);


// 移动到可放置点
    document.addEventListener("dragenter", function (event) {
      console.log("dragenter",event.target)
      // 当可拖动的元素进入可放置的目标高亮目标节点
      if (event.target.className == "dropzone") {
        event.target.style.background = "purple";
      }

    }, false);

// 离开可放置点
    document.addEventListener("dragleave", function (event) {
      console.log("dragleave",event.target)
      // 当拖动元素离开可放置目标节点，重置其背景
      if (event.target.className == "dropzone") {
        event.target.style.background = "";
      }

    }, false);

// 放下 
    document.addEventListener("drop", function (event) {
      console.log("drop",event.dataTransfer)
      // 阻止默认动作（如打开一些元素的链接）
      event.preventDefault();
      // 移动拖动的元素到所选择的放置目标节点
      if (event.target.className == "dropzone") {
        event.target.style.background = "";
        dragged.parentNode.removeChild(dragged);
        event.target.appendChild(dragged);
      }

    }, false);

  </script>
</body>

</html>